var http = require('http');
var createHandler = require('gitee-webhook-handler')
var handler = createHandler({path: '/webhooks_push', secret: '123456'});// post 所需要用到的秘钥

function run_cmd(cmd, args, callback) {
  var spawn = require('child_process').spawn;
  var child = spawn(cmd, args);
  var resp = "";
  child.stdout.on('data', function (buffer) {
    resp += buffer.toString();
  });
  child.stdout.on('end', function () {
    callback(resp)
  });
}

handler.on('error', function (err) {
  console.error('Error:', err.message)
})
handler.on('Push Hook', function (event) {  // 这个地方就是GitHub 和 Gitee 不一样的地方，需要注意
  console.log('Received a push event for %s to %s', event.payload.repository.name, event.payload.ref);
  // console.log(event.payload.head_commit);
  // console.log(JSON.stringify(event.payload,2,2));
  // 分支判断
  if (event.payload.ref === 'refs/heads/master') {
    console.log('deploy master..');
    //记录更新时间
    var date = new Date();
    console.log(date.toLocaleDateString() + ' ' + date.toLocaleTimeString());
    run_cmd('sh', ['./deploy.sh'], function (text) {
      console.log(text)
    });
  }
})
try {
  http.createServer(function (req, res) {
    handler(req, res, function (err) {
      res.statusCode = 404
      res.end('no such location')
    })
  }).listen(7777, function () {
    console.log('开始监听7777端口');
  }) //# 服务监听的端口，可以自行修改
} catch (err) {
  console.error('Error:', err.message)
}